package com.cskaoyan.gateway.controller.user;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.commons.tool.utils.CookieUtil;
import com.mall.user.IKaptchaService;
import com.mall.user.ILoginService;
import com.mall.user.annotation.Anoymous;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dto.*;
import com.mall.user.intercepter.TokenIntercepter;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.ZoneOffset;

/**
 * @author : [Dragon]
 * @createTime : [2022/1/20 14:08]
 * @description :
 */

@RestController
@RequestMapping("user")
public class LoginController {

    @Reference(timeout = 3000, check = false)
    IKaptchaService kaptchaService;

    @Reference(timeout = 3000, check = false)
    ILoginService loginService;


    @Anoymous
    @PostMapping("login")
    public ResponseData userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        //判断验证码是否正确
        KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest();
        String uuid = CookieUtil.getCookieValue(httpServletRequest, "kaptcha_uuid");
        kaptchaCodeRequest.setUuid(uuid);
        kaptchaCodeRequest.setCode(userLoginRequest.getCaptcha());
        KaptchaCodeResponse response = kaptchaService.validateKaptchaCode(kaptchaCodeRequest);
        //验证码正确
        String result;
        if (response.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())) {
            UserLoginResponse userLoginResponse = loginService.validUserLoign(userLoginRequest);
            //账号密码正确
            if ("200".equals(userLoginResponse.getCode())) {
                //将token放入response中
                Cookie cookie = CookieUtil.genCookie(TokenIntercepter.ACCESS_TOKEN, userLoginResponse.getToken(),
                        "/", (int) LocalDateTime.now().plusDays(1).toEpochSecond(ZoneOffset.of("+8")));
                CookieUtil.setCookie(httpServletResponse, cookie);

                // 把username放入

                return new ResponseUtil<>().setData(userLoginResponse, "success");
            }
            result = userLoginResponse.getMsg();
        } else {
            return new ResponseUtil<>().setErrorMsg("验证码错误");
        }
        //账号密码错误
        return new ResponseUtil<>().setErrorMsg(result);
    }

    @GetMapping("login")
    public ResponseData userLoginGet(HttpServletRequest httpServletRequest) {
        String userInfo = (String) httpServletRequest.getAttribute(TokenIntercepter.USER_INFO_KEY);
        JSONObject jsonObject = JSON.parseObject(userInfo);
        UserLoginGetResponse userLoginGetResponse = loginService.getLoginMsg((String) jsonObject.get("uid"));
        UserLoginVO userLoginVO = new UserLoginVO();
        userLoginVO.setUsername(userLoginGetResponse.getUsername());
        userLoginVO.setUid(userLoginGetResponse.getUid());
        return new ResponseUtil<>().setData(userLoginVO, "success");

    }

    @GetMapping("loginOut")
    public ResponseData userLoginOut(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        //删除session域中的userId
        httpServletRequest.removeAttribute(TokenIntercepter.USER_INFO_KEY);
        //删除Cookie中的ACCESS_TOKEN
        Cookie[] cookies = httpServletRequest.getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(TokenIntercepter.ACCESS_TOKEN)) {
                cookie.setMaxAge(0);
                CookieUtil.setCookie(httpServletResponse, cookie);
                cookie.setPath("/");
                httpServletResponse.addCookie(cookie);
            }
        }
        return new ResponseUtil<>().setErrorMsg("退出成功");
    }
}

